﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloudFranceTriple.Models;
using WebMatrix.WebData;

namespace CloudFranceTriple.WebRole.Areas.Forum.Controllers
{
    public class PollAnswerController : BaseController
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();

        private readonly IWebSecurityWrapper _webSecurity;
        public PollAnswerController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public PollAnswerController(IWebSecurityWrapper webSecurity)
            : base(webSecurity)
        {
            this._webSecurity = webSecurity;
        }

        //
        // GET: /Forum/PollAnswer/Index/PollAnswerId
        [AllowAnonymous()]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ChildActionOnly]
        public ActionResult ShowWhoPolledWhat(int id)
        {
            var context = new CloudFranceTriple.WebRole.Models.UsersContext();
            var answer = db.PollAnswerSet.Find(id);

            if (!db.PollSet.Find(answer.Poll_Id).IsPublicPollResult)
                ThrowSecurityException();

            var result = String.Empty;

            String[] pollers = new string[answer.PollUserSet.Count()];
            Int32 counter = 0;
            foreach (CloudFranceTriple.Models.PollUserSet pu in answer.PollUserSet)
            {
                pollers[counter++] = context.UserProfiles.SingleOrDefault(u => u.UserId == pu.UserId).UserName;
            }
            if (counter > 0)
                result = String.Format("({0})", String.Join("; ", pollers.OrderBy(p => p)));

            return PartialView("_ShowWhoPolledWhat", result);
        }

        //
        // GET: /Forum/PollAnswer/Index/PollId
        [AllowAnonymous()]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ChildActionOnly]
        public ActionResult Index(int id)
        {
            var poll = db.PollSet.Find(id);
            if (poll == null) return HttpNotFound();

            ViewBag.Poll_Id = id;
            ViewBag.IsRecuitPoll = poll.IsRecruitPoll;
            ViewBag.IsMemberOnlyPoll = poll.IsMemberOnlyPoll;
            ViewBag.IsPublicPollResult = poll.IsPublicPollResult;

            var _userId = _webSecurity.CurrentUserId;

            if (poll.ForumTopic_Id == null)
            {
                ViewBag.IsAuthor = User.IsInRole("RoleAuthorPollOnPortail");
                ViewBag.IsTopicAuthor = User.IsInRole("RoleAuthorPollOnPortail");
            }
            else
            {
                ViewBag.IsAuthor = CheckAutorRights(db.ForumTopicSet.Find(poll.ForumTopic_Id));
                ViewBag.IsTopicAuthor = (_webSecurity.CurrentUserName == db.ForumTopicSet.Find(poll.ForumTopic_Id).AuthorForumTopic);
            }
            ViewBag.HasPolled = poll.PollAnswerSet.Join(db.PollUserSet.Where(pu2 => pu2.UserId == _userId), answer => answer.Id, pu => pu.PollAnswer_Id, (anwser, pu) => anwser.Id).Count() > 0;
            ViewBag.ShowResults = (DateTime.Compare((poll.CreationDatePoll.AddDays(poll.DurationInDays)), DateTime.UtcNow) < 0);

            var pollanswerset = db.PollAnswerSet.Where(answer => answer.Poll_Id == id).Include("PollUserSet");

            return PartialView(pollanswerset.ToList());
        }

        //
        // GET: /Forum/PollAnswer/Create/PollId
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ChildActionOnly]
        public ActionResult Create(int id)
        {
            Boolean _IsAuthor;
            if (db.PollSet.Find(id).ForumTopic_Id == null)
            {
                _IsAuthor = User.IsInRole("RoleAuthorPollOnPortail");
            }
            else
            {
                _IsAuthor = CheckAutorRights(db.ForumTopicSet.Find(db.PollSet.Find(id).ForumTopic_Id));
            }

            if (!_IsAuthor)
                return null;

            ViewBag.IsAuthor = _IsAuthor;
            ViewBag.Poll_Id = id;
            return PartialView();
        }

        //
        // POST: /Forum/PollAnswer/Create

        [HttpPost]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ValidateAntiForgeryToken]
        public ActionResult Create(PollAnswerSet pollanswerset)
        {
            if (ModelState.IsValid)
            {
                db.PollAnswerSet.Add(pollanswerset);
                db.SaveChanges();
                Boolean IsPollFromPortail = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id == null;
                if (IsPollFromPortail)
                    return RedirectToAction("Index", "Home", new { area = "" });
                else
                    return RedirectToAction("Index", "Post", new { area = "Forum", id = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id });
            }
            ViewBag.Poll_Id = pollanswerset.Poll_Id;
            return View();
        }

        //
        // GET: /Forum/PollAnswer/Edit/5
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Edit(int id = 0)
        {
            PollAnswerSet pollanswerset = db.PollAnswerSet.Find(id);
            if (pollanswerset == null)
            {
                return HttpNotFound();
            }
            Boolean _IsAuthor;
            if (db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id == null)
            {
                _IsAuthor = User.IsInRole("RoleAuthorPollOnPortail");
            }
            else
            {
                _IsAuthor = CheckAutorRights(db.ForumTopicSet.Find(db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id));
            }
            if (!_IsAuthor)
                return null;

            ViewBag.IsAuthor = _IsAuthor;
            ViewBag.Poll_Id = pollanswerset.Poll_Id;
            ViewBag.Topic_Id = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id;
            return View(pollanswerset);
        }

        //
        // POST: /Forum/PollAnswer/Edit/5

        [HttpPost]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(PollAnswerSet pollanswerset)
        {
            if (ModelState.IsValid)
            {
                db.Entry(pollanswerset).State = EntityState.Modified;
                db.SaveChanges();
                Boolean IsPollFromPortail = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id == null;
                if (IsPollFromPortail)
                    return RedirectToAction("Index", "Home", new { area = "" });
                else
                    return RedirectToAction("Index", "Post", new { area = "Forum", id = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id });
            }
            ViewBag.Poll_Id = pollanswerset.Poll_Id;
            return View();
        }

        //
        // GET: /Forum/PollAnswer/Delete/5

        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        public ActionResult Delete(int id = 0)
        {
            PollAnswerSet pollanswerset = db.PollAnswerSet.Find(id);
            if (pollanswerset == null)
            {
                return HttpNotFound();
            }
            Boolean _IsAuthor;
            if (db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id == null)
            {
                _IsAuthor = User.IsInRole("RoleAuthorPollOnPortail");
            }
            else
            {
                _IsAuthor = CheckAutorRights(db.ForumTopicSet.Find(db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id));
            }
            if (!_IsAuthor)
                return null;

            ViewBag.IsAuthor = _IsAuthor;
            ViewBag.Topic_Id = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id;
            return View(pollanswerset);
        }

        //
        // POST: /Forum/PollAnswer/Delete/5

        [HttpPost, ActionName("Delete")]
        [Authorize(Roles = "RoleMember,RoleFans,RoleBaffMember,RoleAdminForum")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            PollAnswerSet pollanswerset = db.PollAnswerSet.Find(id);
            Boolean IsPollFromPortail = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id == null;
            db.PollAnswerSet.Remove(pollanswerset);
            db.SaveChanges();

            if (IsPollFromPortail)
                return RedirectToAction("Index", "Home", new { area = "" });
            else
                return RedirectToAction("Index", "Post", new { area = "Forum", id = db.PollSet.Find(pollanswerset.Poll_Id).ForumTopic_Id });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}